package vip.sweet.web.handler;

import cn.hutool.json.JSONUtil;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import vip.sweet.common.enums.ResponseEnum;
import vip.sweet.common.response.CommonResponse;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author ASUS
 * @Date 2025/7/13 17:23
 * @Descripition 用于认证失败处理
 */
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException {
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        CommonResponse result = CommonResponse.error(ResponseEnum.UNAUTHORIZED, "认证失败,请先登录");
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();
        outputStream.write(JSONUtil.toJsonStr(result).getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}
